import http.client
import json
import datetime
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

#领取和归还记录列表
def doGetrecords(iType):
    #2=第一次入库 3=借出 4=归还
    try:
        logger.info('151:领取和归还记录列表')

        typename="第一次入库"
        if(iType==3):
            typename="借出"
        if(iType==4):
            typename="归还"

        # 获取当前日期
        curr_date = datetime.datetime.now().date()

        # 计算前3天的日期
        delta =datetime.timedelta(days=1)
        begdate = curr_date - delta

        delta = datetime.timedelta(days=0)
        enddate= curr_date - delta

        billno=global_site+enddate.strftime('%Y%m%d')+"0001"
        print(billno)

        # 查询当前智能柜数据
        sql = " select foperator,fequipmentbarcode from i_ts_cabinet"
        sql = sql + " where fsite_no='" + global_site + "'"
        #logger.info('151:' + sql)
        conn, cursor = postsql_utility.get_conn()
        data_2 = postsql_utility.select(sql=sql, cursor=cursor)

        for j1 in range(len(data_2)):
            ibox_id = data_2[j1][0]
            ibox_code = data_2[j1][1]
            try:
                httpconn = http.client.HTTPSConnection(global_url)
                payload = ''
                headers = {
                    'app-id': global_appid,
                    'app-key': global_appkey
                }
                url = "/openapi/summary/inoutList?startTime=" + str(begdate) + "&endTime=" + str(
                    enddate) + "&danger=1&pageNo=1&pageSize=200&type="+str(iType)+"&cabinetId="+str(ibox_id)
                ##print("151:领取和归还记录列表:"+url)
                httpconn.request("GET", url, payload, headers)
                res = httpconn.getresponse()
                data = res.read()
                data = data.decode("utf-8")
                #print(data)
                #logger.info('151:' + data.decode("utf-8"))
                httpconn.close()

                # 遍历当前获取的数据,i_warehouse_inv
                json_str = json.loads(data)
                ierrCode = json_str["errCode"]
                if (ierrCode == 200):
                    irec_num = json_str["totalItems"]
                    if (irec_num > 0):

                        sqllist = []
                        if ((iType == 4) or (iType==2)):
                            #对应界面的　物料归还
                            billno="I"+str(billno)
                            sql="delete from i_tc_takeout_head"
                            sql=sql+" where fbillno='"+billno+"';"
                            sqllist.append(sql)

                            sql="insert into i_tc_takeout_head(fbillno,fsite_no,ftakeuser,ftakedate,fstockno"
                            sql=sql+",fitemcount,fpiececount,ftotalamt,fexplanation"
                            sql=sql+",fupddate,foperator,fcheckdate,fcheckuser"
                            sql=sql+",fbillstate,fsrcbillno,fbilltype) "
                            sql=sql+"values('"+billno+"','"+global_site+"',0,'"+str(enddate)+"','"+global_stock+"'"
                            sql=sql+",1,1,0,'"+typename+"'"
                            sql=sql+",now(),0,now(),0"
                            sql=sql+",2,"+str(iType)+",0);"
                            sqllist.append(sql)

                            sql = "delete from i_tc_takeout_detail"
                            sql = sql + " where fbillno='" + billno + "';"
                            sqllist.append(sql)
                        else:
                            # 对应界面的　物料领取
                            billno = "O" + str(billno)
                            sql = "delete from i_tc_takein_head"
                            sql = sql + " where fbillno='" + billno + "';"
                            sqllist.append(sql)

                            sql = "insert into i_tc_takein_head(fbillno,fsite_no,ftakeuser,ftakedate,fstockno"
                            sql = sql + ",fitemcount,fpiececount,ftotalamt,fexplanation"
                            sql = sql + ",fupddate,foperator,fcheckdate,fcheckuser"
                            sql = sql + ",fbillstate,fbilltype,fsrcbillno) "
                            sql = sql + "values('" + billno + "','" + global_site + "',0,'" + str(enddate) + "','"+global_stock+"'"
                            sql = sql + ",1,1,0,'"+typename+"'"
                            sql = sql + ",now(),0,now(),0"
                            sql = sql + ",2,0,'');"
                            sqllist.append(sql)

                            sql = "delete from i_tc_takein_detail"
                            sql = sql + " where fbillno='" + billno + "';"
                            sqllist.append(sql)

                        biz_data=json_str["data"]
                        for j1 in range(len(biz_data)):
                            irfid = biz_data[j1]["materiel"]["rfidCode"]
                            igood_no = biz_data[j1]["materiel"]["id"]
                            iweight = biz_data[j1]["weight"]     #剩余量
                            iuseWeight=biz_data[j1]["useWeight"] #使用量
                            timestamp1 = biz_data[j1]["materiel"]["recordTime"]
                            timestamp2 = str(timestamp1)[:10]  # 前１０位就是时间戳
                            # print(timestamp2)
                            procdate = datetime.datetime.fromtimestamp(int(timestamp2)).strftime('%Y-%m-%d %H:%M:%S')
                            if((iType == 4) or (iType==2)):
                                sql="insert into i_tc_takeout_detail(fbillno,fline,frfidbarcode,fgoodno,fbuyprice"
                                sql=sql+",fqty,ftotamt,fboxbarcode,fcabbarcode"
                                sql=sql+",foperator,fupddate,fmemo,foutqty,fprocdate"
                                sql=sql+",fpackno) "
                                sql=sql+"values('"+billno+"',"+str(j1)+",'"+irfid+"',"+str(igood_no)+",0"
                                sql=sql+","+str(iuseWeight)+",0,0,'"+ibox_code+"'"
                                sql=sql+",0,'"+str(procdate)+"','',"+str(iweight)+",'"+procdate+"',0);"
                            else:
                                sql = "insert into i_tc_takein_detail(fbillno,fline,frfidbarcode,fgoodno,fbuyprice"
                                sql = sql + ",fqty,ftotamt,fboxbarcode,fcabbarcode"
                                sql = sql + ",foperator,fupddate,fmemo,fprocdate)"
                                sql = sql + "values('" + billno + "'," + str(j1) + ",'" + irfid + "'," + str(igood_no) + ",0"
                                sql = sql + "," + str(iuseWeight) + ",0,0,'" + ibox_code + "'"
                                sql = sql + ",0,'" + str(procdate) + "',"+str(iweight)+",'" + procdate + "');"
                            sqllist.append(sql)

                        if (len(sqllist) > 0):
                            i = postsql_utility.executemuch(sqllist, cursor=cursor, connect=conn)

                            if i != "OK":
                                logger.info('152:失败' + str(i))
                            else:
                                logger.info('152:成功' + str(i))

                    else:
                        print(f"没有业务数据:{ibox_id}")
                else:
                    print(json_str["errMsg"])

            except Exception as e:
                logger.info('151:错误1'+str(e))

    except Exception as e:
        logger.info('151:错误2'+str(e))

#
#doGetrecords(2)